<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>风险附件管理</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/dropzone@5.9.3/dist/min/dropzone.min.css">
    <style>
        .dropzone {
            border: 2px dashed #0087F7;
            border-radius: 5px;
            background: #F9FDFF;
            min-height: 150px;
            padding: 20px;
            margin-bottom: 20px;
        }
        .preview-container {
            display: flex;
            flex-wrap: wrap;
            margin-top: 15px;
        }
        .preview-item {
            margin: 10px;
            padding: 5px;
            border: 1px solid #ddd;
            border-radius: 4px;
            text-align: center;
            width: 150px;
        }
        .preview-item .preview-image {
            width: 100px;
            height: 100px;
            object-fit: cover;
            margin-bottom: 5px;
        }
        .preview-item .preview-icon {
            font-size: 48px;
            color: #6c757d;
            margin-bottom: 5px;
        }
        .preview-item .preview-name {
            font-size: 12px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }
    </style>
</head>
<body>
    <div class="container mt-4">
        <div class="row mb-3">
            <div class="col">
                <h2>风险附件管理</h2>
                <nav aria-label="breadcrumb">
                    <ol class="breadcrumb">
                        <li class="breadcrumb-item"><a th:href="@{/project/list}">项目列表</a></li>
                        <li class="breadcrumb-item"><a th:href="@{/risk/project/{id}(id=${risk.projectId})}">项目风险</a></li>
                        <li class="breadcrumb-item"><a th:href="@{/risk/{id}(id=${risk.id})}">风险详情</a></li>
                        <li class="breadcrumb-item active" aria-current="page">附件管理</li>
                    </ol>
                </nav>
            </div>
        </div>
        
        <div class="row mb-4">
            <div class="col">
                <div class="card">
                    <div class="card-header">
                        <h5 class="mb-0">风险信息</h5>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-6">
                                <p><strong>风险标题：</strong> <span th:text="${risk.title}"></span></p>
                                <p><strong>风险类型：</strong> 
                                    <span th:if="${risk.type == 1}">技术风险</span>
                                    <span th:if="${risk.type == 2}">管理风险</span>
                                    <span th:if="${risk.type == 3}">商业风险</span>
                                    <span th:if="${risk.type == 4}">外部风险</span>
                                </p>
                            </div>
                            <div class="col-md-6">
                                <p><strong>状态：</strong>
                                    <span th:if="${risk.status == 1}" class="badge badge-secondary">已识别</span>
                                    <span th:if="${risk.status == 2}" class="badge badge-primary">已分析</span>
                                    <span th:if="${risk.status == 3}" class="badge badge-info">已计划</span>
                                    <span th:if="${risk.status == 4}" class="badge badge-warning">已处理</span>
                                    <span th:if="${risk.status == 5}" class="badge badge-success">已解决</span>
                                </p>
                                <p><strong>责任人：</strong> <span th:text="${owner != null ? owner.realName : '未指定'}"></span></p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="row mb-4">
            <div class="col">
                <div class="card">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h5 class="mb-0">上传附件</h5>
                    </div>
                    <div class="card-body">
                        <div id="dropzone-upload" class="dropzone">
                            <div class="dz-message" data-dz-message>
                                <span>拖放文件到此处或点击上传</span>
                                <span class="d-block mt-2">支持各类文档、图片等文件（最大10MB）</span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="row">
            <div class="col">
                <div class="card">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h5 class="mb-0">附件列表</h5>
                    </div>
                    <div class="card-body">
                        <div id="attachment-container">
                            <div class="text-center py-3">
                                <i class="fa fa-spinner fa-spin fa-2x"></i>
                                <p class="mt-2">加载附件数据...</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 附件预览模态框 -->
    <div class="modal fade" id="previewModal" tabindex="-1" role="dialog" aria-labelledby="previewModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="previewModalLabel">文件预览</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body" id="preview-content">
                    <!-- 预览内容将在这里显示 -->
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
                    <a href="#" class="btn btn-primary" id="download-btn" target="_blank">下载</a>
                </div>
            </div>
        </div>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/dropzone@5.9.3/dist/min/dropzone.min.js"></script>
    <script th:inline="javascript">
        // 阻止Dropzone自动初始化
        Dropzone.autoDiscover = false;
        
        $(document).ready(function() {
            // 加载附件数据
            loadAttachments();
            
            // 初始化Dropzone
            const myDropzone = new Dropzone("#dropzone-upload", {
                url: "/risk-management/api/risk-attachments/" + [[${risk.id}]] + "/upload",
                paramName: "file", // 与后端接收参数名一致
                maxFilesize: 10, // 最大文件大小，单位MB
                acceptedFiles: null, // 允许任何类型的文件
                addRemoveLinks: true,
                dictRemoveFile: "删除",
                dictCancelUpload: "取消",
                dictDefaultMessage: "拖放文件到此处或点击上传",
                init: function() {
                    this.on("success", function(file, response) {
                        // 上传成功后刷新附件列表
                        loadAttachments();
                    });
                    this.on("error", function(file, errorMessage) {
                        if (typeof errorMessage === 'string') {
                            alert("上传失败: " + errorMessage);
                        } else if (errorMessage.message) {
                            alert("上传失败: " + errorMessage.message);
                        } else {
                            alert("上传失败，请稍后重试");
                        }
                    });
                }
            });
        });
        
        // 加载附件数据
        function loadAttachments() {
            const riskId = [[${risk.id}]];
            $.ajax({
                url: '/risk-management/api/risk-attachments/' + riskId,
                type: 'GET',
                dataType: 'json',
                success: function(attachments) {
                    let html = '';
                    if (attachments && attachments.length > 0) {
                        html = '<div class="table-responsive">' +
                               '<table class="table table-hover">' +
                               '<thead><tr>' +
                               '<th>文件名</th><th>类型</th><th>大小</th><th>上传时间</th><th>上传者</th><th>操作</th>' +
                               '</tr></thead><tbody>';
                        
                        attachments.forEach(function(attachment) {
                            const fileSize = formatFileSize(attachment.fileSize);
                            const uploadTime = new Date(attachment.uploadTime).toLocaleString();
                            const isImage = attachment.fileType && attachment.fileType.startsWith('image/');
                            
                            html += '<tr>' +
                                '<td>' + attachment.originalFileName + '</td>' +
                                '<td>' + (attachment.fileType || '-') + '</td>' +
                                '<td>' + fileSize + '</td>' +
                                '<td>' + uploadTime + '</td>' +
                                '<td>' + attachment.uploadBy + '</td>' +
                                '<td>' +
                                '<button class="btn btn-sm btn-secondary mr-1" onclick="previewAttachment(' + attachment.id + ', \'' + attachment.fileType + '\', \'' + attachment.originalFileName + '\')" title="预览"><i class="fa fa-eye"></i></button>' +
                                '<a href="/risk-management/api/risk-attachments/download/' + attachment.id + '" class="btn btn-sm btn-info mr-1" title="下载"><i class="fa fa-download"></i></a>' +
                                '<button class="btn btn-sm btn-danger" onclick="deleteAttachment(' + attachment.id + ')" title="删除"><i class="fa fa-trash"></i></button>' +
                                '</td>' +
                                '</tr>';
                        });
                        
                        html += '</tbody></table></div>';
                        
                        // 增加图片预览展示区
                        html += '<div class="mt-4"><h6>附件预览</h6><div class="preview-container">';
                        
                        attachments.forEach(function(attachment) {
                            const isImage = attachment.fileType && attachment.fileType.startsWith('image/');
                            const isPdf = attachment.fileType === 'application/pdf';
                            const isDoc = attachment.fileType && (
                                attachment.fileType.includes('word') || 
                                attachment.fileType.includes('excel') || 
                                attachment.fileType.includes('powerpoint')
                            );
                            
                            let iconClass = 'fa-file';
                            if (isPdf) iconClass = 'fa-file-pdf-o';
                            else if (isDoc) iconClass = 'fa-file-text-o';
                            
                            html += '<div class="preview-item">';
                            
                            if (isImage) {
                                html += '<img src="/risk-management/api/risk-attachments/download/' + attachment.id + '" alt="' + attachment.originalFileName + '" class="preview-image">';
                            } else {
                                html += '<i class="fa ' + iconClass + ' preview-icon"></i>';
                            }
                            
                            html += '<div class="preview-name">' + attachment.originalFileName + '</div>';
                            html += '<div><a href="/risk-management/api/risk-attachments/download/' + attachment.id + '" class="btn btn-sm btn-info mt-1">下载</a></div>';
                            html += '</div>';
                        });
                        
                        html += '</div></div>';
                    } else {
                        html = '<p class="text-center">暂无附件</p>';
                    }
                    
                    $('#attachment-container').html(html);
                },
                error: function() {
                    $('#attachment-container').html('<p class="text-center text-danger">加载附件数据失败</p>');
                }
            });
        }
        
        // 预览附件
        function previewAttachment(attachmentId, fileType, fileName) {
            const previewContent = $('#preview-content');
            const downloadBtn = $('#download-btn');
            
            // 设置下载链接
            downloadBtn.attr('href', '/risk-management/api/risk-attachments/download/' + attachmentId);
            
            // 根据文件类型设置预览内容
            if (fileType && fileType.startsWith('image/')) {
                previewContent.html('<img src="/risk-management/api/risk-attachments/download/' + attachmentId + '" class="img-fluid" alt="' + fileName + '">');
            } else if (fileType === 'application/pdf') {
                previewContent.html('<iframe src="/risk-management/api/risk-attachments/download/' + attachmentId + '" width="100%" height="500px"></iframe>');
            } else {
                previewContent.html('<div class="text-center"><i class="fa fa-file fa-5x mb-3"></i><p>无法预览该类型文件，请下载后查看</p></div>');
            }
            
            // 显示模态框
            $('#previewModal').modal('show');
        }
        
        // 删除附件
        function deleteAttachment(attachmentId) {
            if (confirm('确定要删除此附件吗？')) {
                $.ajax({
                    url: '/risk-management/api/risk-attachments/' + attachmentId,
                    type: 'DELETE',
                    success: function() {
                        loadAttachments();
                    },
                    error: function() {
                        alert('删除附件失败');
                    }
                });
            }
        }
        
        // 格式化文件大小
        function formatFileSize(bytes) {
            if (bytes === 0) return '0 B';
            const k = 1024;
            const sizes = ['B', 'KB', 'MB', 'GB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        }
    </script>
</body>
</html> 